package com.sz.youban.dt.service.idcard;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.feilong.core.Validator;
import com.feilong.core.bean.PropertyUtil;
import com.sz.youban.dt.entity.idcard.CardIdCode;
import com.sz.youban.dt.entity.idcard.CardIdView;
import com.sz.youban.dt.entity.idcard.DtCardIdInfo;
import com.sz.youban.dt.entity.idcard.DtCardIdInfoLog;
import com.sz.youban.dt.entity.result.ResultData;
import com.sz.youban.dt.entity.result.ResultDataEnum;
import com.sz.youban.dt.interf.idcard.IDtCardIdInfoLogService;
import com.sz.youban.dt.interfs.idcard.IDtCardIdInfoService;
import com.sz.youban.dt.service.idcard.mapper.DtCardIdInfoMapper;
import com.sz.youban.dt.service.utils.HttpUtils;
import com.sz.youban.dt.service.utils.StringUtil;

/**
 * <p>
 * 身份证信息 服务实现类
 * </p>
 *
 * @author huiquan
 * @since 2017-06-05
 */
@Service
public class DtCardIdInfoServiceImpl extends ServiceImpl<DtCardIdInfoMapper, DtCardIdInfo> implements IDtCardIdInfoService {
	
	private final Logger log = LoggerFactory.getLogger(this.getClass());

	@Value("${idcardhost}")
	private String idcardhost;
	
	@Value("${idcardpath}")
	private String idcardpath;
	
	@Value("${idcardappcode}")
	private String idcardappcode;
	
	@Value("${idcardmethod}")
	private String idcardmethod;
	
	@Autowired
	private IDtCardIdInfoLogService cardIdInfoLogService;
	
	@Override
	public ResultData checkIdCard(String name,String cardno) {
		ResultData resultData = new ResultData();
		//先查询数据库是否有数据，如果有则返回
		Map<String,Object> columnMap = new HashMap<>();
		columnMap.put("card_id", StringUtil.encrypt(cardno));
		columnMap.put("real_name", name);
		List<DtCardIdInfo> cardIdList = baseMapper.selectByMap(columnMap);
		if(Validator.isNotNullOrEmpty(cardIdList) && Validator.isNotNullOrEmpty(cardIdList.get(0)))
		{
			resultData.setCode(ResultDataEnum.OK.getCode());
			resultData.setMsg(CardIdCode.pass.getDesc());
			cardIdList.get(0).setCardId(cardno);
			resultData.setInfo(cardIdList.get(0));
			return resultData;
		}
		//如果没在数据库找到，则调用第三方接口查询，查询后将数据存入库中
	    Map<String, String> headers = new HashMap<String, String>();
	    headers.put("Authorization", "APPCODE " + idcardappcode);
	    Map<String, String> querys = new HashMap<String, String>();
	    querys.put("cardno", cardno);
	    querys.put("name", name);
	    String cardDesc = "";
		DtCardIdInfo cardIdInfo = null;
	    try {
	    	//访问第三方实名认证接口
	    	HttpResponse response = HttpUtils.doGet(idcardhost, idcardpath, idcardmethod, headers, querys);
	    	//获取response的body
	    	String result = EntityUtils.toString(response.getEntity());
	    	log.info("===================checkIdcard result:{}===================",result);
		    CardIdView cardIdView = JSON.toJavaObject(JSONObject.parseObject(result), CardIdView.class);
			if(cardIdView.getCode() == CardIdCode.errorParam.getCode()){
				cardDesc = CardIdCode.errorParam.getDesc();
			}else if(cardIdView.getCode() == CardIdCode.noIdCard.getCode()){
				cardDesc = CardIdCode.noIdCard.getDesc();
			}else if(cardIdView.getCode() == CardIdCode.fail.getCode()){
				cardDesc = CardIdCode.fail.getDesc();
			}else if(cardIdView.getCode() == CardIdCode.sysMaintain.getCode()){
				cardDesc = CardIdCode.sysMaintain.getDesc();
			}else if(cardIdView.getCode() == CardIdCode.pass.getCode()){
				//如果身份证号和姓名一致，则存入数据库
				cardIdInfo = cardIdView.getData();
				cardDesc = CardIdCode.pass.getDesc();
				cardIdInfo.setTsp(new Date());
				cardIdInfo.setRealName(name);
				//加密身份证
				cardIdInfo.setCardId(StringUtil.encrypt(cardno));
				baseMapper.insert(cardIdInfo);
				//如果身份证一致则返回10000
				cardIdView.setCode(ResultDataEnum.OK.getCode());
				//还原身份证返回给前端
				cardIdInfo.setCardId(cardno);
			}else{
				//如果没有指定的code，则显示系统维护
				cardDesc=CardIdCode.sysMaintain.getDesc();
			}
			//存入日志表
			DtCardIdInfoLog cardIdInfoLog = new DtCardIdInfoLog();
			PropertyUtil.copyProperties(cardIdInfo,cardIdInfoLog,"cardId","realName","sex","birthday","isFaceCheck","address");
			cardIdInfoLog.setRetCode(cardIdView.getCode());
			cardIdInfoLog.setRetMsg(cardDesc);
			cardIdInfoLog.setTsp(new Date());
			cardIdInfoLogService.insert(cardIdInfoLog);
			
			resultData.setCode(cardIdView.getCode());
			resultData.setMsg(cardDesc);
			resultData.setInfo(cardIdInfo);
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
		return resultData;
	}
	
	
	
	public static void main(String[] args) {
//		String result = "{\"isok\":1,\"code\":3,\"data\":{\"err\":-1,\"address\":\"\",\"sex\":\"\",\"birthday\":\"\"}}";
//		String result = "{\"isok\":1,\"code\":8,\"data\":{\"err\":0,\"address\":\"\u5C71\u897F\u7701\u957F\u6CBB\u5E02\u6C81\u53BF\",\"sex\":\"M\",\"birthday\":\"1987-08-17\"}}";
		String result = "{\"isok\":1,\"code\":1,\"data\":{\"err\":0,\"address\":\"\u5E7F\u4E1C\u7701\u63ED\u9633\u5E02\u6995\u57CE\u533A\",\"sex\":\"M\",\"birthday\":\"1991-08-29\"}}";
		CardIdView cardIdView = JSON.toJavaObject(JSONObject.parseObject(result), CardIdView.class);
		Map<String,Object> returnMap = new HashMap<>();
		String cardDesc = "";
		DtCardIdInfo cardIdInfo = null;
		if(cardIdView.getCode() == CardIdCode.errorParam.getCode()){
			cardDesc = CardIdCode.errorParam.getDesc();
		}else if(cardIdView.getCode() == CardIdCode.noIdCard.getCode()){
			cardDesc = CardIdCode.noIdCard.getDesc();
		}else if(cardIdView.getCode() == CardIdCode.fail.getCode()){
			cardDesc = CardIdCode.fail.getDesc();
		}else if(cardIdView.getCode() == CardIdCode.sysMaintain.getCode()){
			cardDesc = CardIdCode.sysMaintain.getDesc();
		}else if(cardIdView.getCode() == CardIdCode.pass.getCode()){
			//如果身份证号和姓名一致，则存入数据库
			cardIdInfo = cardIdView.getData();
			cardDesc = CardIdCode.pass.getDesc();
			cardIdInfo.setTsp(new Date());
//			cardIdInfo.setRealName(name);
//			cardIdInfo.setCardId(cardno);
//			baseMapper.insert(cardIdInfo);
		}else{
			cardDesc=CardIdCode.sysMaintain.getDesc();;
		}
		returnMap.put("code", cardIdView.getCode());
		returnMap.put("msg", cardDesc);
		returnMap.put("data", cardIdInfo);
		System.out.println(returnMap);
	}
	
}
